<template>
  <div class="app-container">
    <!-- 表单 -->
    <el-form :model="form" ref="form" label-width="120px">
      <el-form-item label="元器件类型" prop="typeName">
        <el-select v-model="form.typeName" placeholder="请选择元器件类型">
          <el-option
            v-for="item in componentTypes"
            :key="item.id"
            :label="item.typeName"
            :value="item.typeName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="型号" prop="labelName">
        <el-select v-model="form.labelName" placeholder="请选择型号">
          <el-option
            v-for="item in componentLabels"
            :key="item.id"
            :label="item.labelName"
            :value="item.labelName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工况id" prop="conditionId">
        <el-select v-model="form.conditionId" placeholder="请选择工况id">
          <el-option
            v-for="item in componentConditions"
            :key="item.id"
            :label="item.conditionId"
            :value="item.conditionId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择文件" prop="file">
        <el-upload
          action=""
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          :limit="1"
          accept=".xlsx"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="preprocessData">预处理</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { listComponentTypes, listComponentLabels, listComponentConditions, saveCharacteristicFilePath } from "@/api/bearing/componentdata";
import XLSX from 'xlsx';

export default {
  name: "DataPreprocessing",
  data() {
    return {
      form: {
        typeName: '',
        labelName: '',
        conditionId: null,
        file: null,
      },
      componentTypes: [],
      componentLabels: [],
      componentConditions: [],
      fileList: []
    };
  },
  created() {
    this.getComponentTypes();
    this.getComponentLabels();
    this.getComponentConditions();
  },
  methods: {
    getComponentTypes() {
      listComponentTypes().then(response => {
        this.componentTypes = response.data;
      });
    },
    getComponentLabels() {
      listComponentLabels().then(response => {
        this.componentLabels = response.data;
      });
    },
    getComponentConditions() {
      listComponentConditions().then(response => {
        this.componentConditions = response.data;
      });
    },
    handleFileChange(file) {
      if (file.raw) {
        this.form.file = file.raw;
        console.log('文件对象已正确传递:', this.form.file);
      } else {
        console.error('文件对象未正确传递');
      }
    },
    async preprocessData() {
  if (!this.form.file) {
    this.$message.error('请先选择文件');
    return;
  }

  const reader = new FileReader();
  reader.onload = async (e) => {
    if (!e.target || !e.target.result) {
      console.error('FileReader 读取结果为空');
      return;
    }

    console.log('FileReader 读取结果:', e.target.result);

    const data = new Uint8Array(e.target.result);
    try {
      const workbook = XLSX.read(data, { type: 'array' });
      const sheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[sheetName];

      // 获取原始数据
      const originalData = XLSX.utils.sheet_to_json(worksheet);
      console.log('原始数据:', originalData);

      // 预处理数据
      let processedData = [];
      if (this.form.typeName === 'MOSFET') {
        processedData = originalData.map(row => ({
          ...row,
          resistance: row.drainSourceVoltage / row.drainCurrent
        }));
      }
      console.log('预处理数据:', processedData);

      // 将处理后的数据写入新的 xlsx 文件
      const newWorksheet = XLSX.utils.json_to_sheet(processedData);
      const newWorkbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(newWorkbook, newWorksheet, 'Processed Data');

      // 保存到 D 盘的 characteristicfile 文件夹下
      const filePath = 'D:/characteristicfile/processed_data.xlsx';
      XLSX.writeFile(newWorkbook, filePath);
      console.log('文件已保存到:', filePath);

      // 将路径插入到 componentdata 表中
      await this.saveToDatabase(filePath);

      this.$message.success('预处理完成并已保存到数据库');
    } catch (error) {
      console.error('XLSX 读取或处理文件时出错:', error);
      this.$message.error('文件读取或处理失败，请稍后再试');
    }
  };

  reader.onerror = (e) => {
    console.error('FileReader 读取文件时出错', e);
  };

      // 使用 readAsArrayBuffer 读取文件数据
      reader.readAsArrayBuffer(this.form.file);
    },
    async saveToDatabase(filePath) {
      try {
        const params = {
          typeName: this.form.typeName,
          labelName: this.form.labelName,
          conditionId: this.form.conditionId,
          characteristicFilePath: filePath
        };
        await saveCharacteristicFilePath(params);
      } catch (error) {
        console.error(error);
        this.$message.error('保存到数据库失败，请稍后再试');
      }
    }
  }
};
</script>
